<?php

class AdminController extends Zend_Controller_Action
{

    public function init()
    {
        $disco = new Application_Model_DbTable_Administrator();
        $this->view->disco = $disco->getAllDisco();

        /* Initialize action controller here */
        require_once "models/Db/Event_db.php";
        require_once "models/Utility/Utility.php";

        $utility_handle = new Utility();
        $eventHandle    = new Event_db();
        
        $pivaList = $eventHandle->getAllPiva();
        foreach ($pivaList as $pivaList2){
                $piva = $pivaList2['piva'];
                $temp = $eventHandle->getUniqueNamebyPiva($piva);
                $allDisco[$piva] = array ($temp['unique_name'], $temp['name']);
        }

        $allDisco = $utility_handle->subval_sort($allDisco,0);
        $this->view->allDisco = $allDisco;

        foreach ($pivaList as $pivaList2){
            $piva = $pivaList2['piva'];
            $temp = $eventHandle->getPaeseDsicoByPiva($piva);
            $paese[$piva] = $temp['paese'];
        }
        $this->view->paese = array_unique($paese);


        $category = $eventHandle->getAllCategory();
        $this->view->category = $category;
//                print_r($category);

        $zonaList = array('Brescia','Verona','Mantova','Cremona');
        $this->view->zonaList = $zonaList;
    }

    public function indexAction()
    {
        // action body
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $id = $auth->getIdentity()->id;
            
            $admin = new Application_Model_DbTable_Administrator();
            
            $club = $admin->getClub($id);
            
            $this->view->admin = $admin->getAdmin($id);
            $this->view->club = $club;
    
    }}

    public function getDiscoForm($piva)
    {
        $form = new Zend_Form();
        $form->addAttribs(array(
          'onSubmit' => 'editor.post();datepicker.post()', 
        ));

        $form->setAction('/Admin/create-success-disco/piva/' . $piva);
        $form->setMethod('post');
        $form->setDescription("Create disco event");

        //Add Elements
        //Create title of event
        $form->addElement('text', 'titolo');
        $titleElement = $form->getElement('titolo');
        $titleElement->setLabel('Titolo evento:');
        $titleElement->setRequired(true);

        //Create description of event
        $form->addElement('textarea', 'descrizione');
        $descriptionElement = $form->getElement('descrizione');
        $descriptionElement->setLabel('Descrizione dell\'evento:');
        $descriptionElement->setRequired(true);
        $descriptionElement->setAttrib('id', 'tagedit');

        //Data inizio
        $form->addElement('text', 'data_inizio');
        $dateelement = $form->getElement('data_inizio');
        $dateelement->setLabel('Data inizio dell\'evento:');
        $dateelement->setAttrib('id', 'datepicker');
        $dateelement->setAttrib('name', 'data_inizio');
        $dateelement->setAttrib('class', 'bottomcalendar');
        $dateelement->setRequired(true);
       //       ->addValidator(
       //                 new Zend_Validate_Date()
       // );
        
      /*  // altro datepicker
        $elem = new ZendX_JQuery_Form_Element_DatePicker(
                "datePicker1", array("label" => "Data inizio dell\' evento: zend")
            );
        $elem->setJQueryParam('dateFormat', 'yy-mm-dd');
        $form->addElement($elem);
*/
        
        //create table
       /* $form->addElement('text', 'tavoli');
        $tableElement = $form->getElement('tavoli');
        $tableElement->setLabel('Numero tavoli disponibili:');
        $tableElement->setRequired(true)
                ->addValidator(
                        new Zend_Validate_Digits());

        //create bottle
        $form->addElement('text', 'bottle');
        $bottleElement = $form->getElement('bottle');
        $bottleElement->setLabel('Numero bottiglie disponibili:');
        $bottleElement->setRequired(true)
                                ->addValidator(
                        new Zend_Validate_Digits());
       */ /*
          //create P.IVA
          $form->addElement('text', 'piva');
          $pivaElement = $form->getElement('piva');
          $pivaElement->setLabel('P.IVA:');
          $pivaElement->setRequired(true);
         */
        //create status (default is active)
        $form->addElement('hidden', 'status');
        $statusElement = $form->getElement('status');
        $statusElement->setValue('1');

        // image upload
        $element = new Zend_Form_Element_File('image');
        $element->setLabel('Seleziona l\'immagine');
        $form->addElement($element, 'image');

        // select if prenotation is enabled
        $form->addElement('checkbox', 'prenorno');
        $pren=$form->getElement('prenorno');
        $pren->setLabel('Evento prenotabile');

        //submit
        $form->addElement('submit', 'submit');
        $submitButton = $form->getElement('submit');
        $submitButton->setLabel('Crea l\'Evento!');

        return $form;
    }

    public function getDiscoTextForm($discoList, $id, $piva)
    {

        $form = new Zend_Form();

        $form->setAction('/Admin/edit-success-disco/piva/' . $piva);
        $form->setMethod('post');
        $form->setDescription("Edit disco event");
        $form->addAttribs(array(
          'onSubmit' => 'editor.post();',
        ));

        //Add Elements
        //Create title of event
        $form->addElement('text', 'titolo');
        $titleElement = $form->getElement('titolo');
        $titleElement->setLabel('Titolo evento:');
        $titleElement->setValue($discoList['titolo']);
        $titleElement->setRequired(true);

        //Create description of event
        $form->addElement('text', 'descrizione');
        $descriptionElement = $form->getElement('descrizione');
        $descriptionElement->setLabel('Descrizione dell\'evento:');
        $descriptionElement->setValue(html_entity_decode($discoList['descrizione']));
        $descriptionElement->setRequired(true);
        $descriptionElement->setAttrib('id', 'tagedit');

        
        //Create description of event
        $form->addElement('text', 'data_inizio');
        $dateelement = $form->getElement('data_inizio');
        $dateelement->setLabel('Data inizio dell\'evento:');
        $dateelement->setAttrib('id', 'datep');
        $dateelement->setAttrib('name', 'data_inizio');
        $dateelement->setAttrib('class', 'bottomcalendar');
        //echo "Data inizio: " . $discoList['data_inizio'];
        $dateelement->setValue($discoList['data_inizio']);
       
        

   /*     //create table
        $form->addElement('text', 'tavoli');
        $tableElement = $form->getElement('tavoli');
        $tableElement->setLabel('Numero tavoli disponibili:');
        $tableElement->setValue($discoList['tavoli']);
        $tableElement->setRequired(true)
        ->addValidator(
                new Zend_Validate_Digits());

        //create bottle
        $form->addElement('text', 'bottle');
        $bottleElement = $form->getElement('bottle');
        $bottleElement->setLabel('Numero bottiglie disponibili:');
        $bottleElement->setValue($discoList['bottle']);
        $tableElement->setRequired(true)
        ->addValidator(
                new Zend_Validate_Digits());
      */
        //create status (default is active)
        $form->addElement('hidden', 'status');
        $statusElement = $form->getElement('status');
        $statusElement->setValue('1');
        
        // select if prenotation is enabled
        $form->addElement('checkbox', 'prenorno');
        $pren=$form->getElement('prenorno');
        $pren->setLabel('Evento prenotabile')
                ->setValue($discoList['pren']);

        //submit
        $form->addElement('submit', 'submit');
        $submitButton = $form->getElement('submit');
        $submitButton->setLabel('Modifica l\'Evento!');

        $form->addElement('hidden', 'id');
        $idElement = $form->getElement('id');
        $idElement->setValue($id);

        return $form;
    }

    public function createDiscoEventAction()
    {
        //Check if the user is logged in
        $auth = Zend_Auth::getInstance();
            if (!$auth->hasIdentity()) {
                echo "Non sei autorizzato.";
                
            } else {
            //Fetch the user's id
            //Fetch the users information
            $id = $auth->getIdentity()->id;

           $piva = $this->_getParam('piva','guest');
           $form=$this->getDiscoForm($piva);
           $this->view->form = $form;
           $this->view->piva = $piva;
    
    }}

    
    public function getDiscoImageForm($id_evento)
    {

        $form = new Zend_Form();

        $form->setAction('/Admin/edit-success-disco-image/id/' . $id_evento);
        $form->setMethod('post');
        $form->setDescription("Edit image event");
        // image upload **** prendi anche l'immagine dall'altra tabella
        $element = new Zend_Form_Element_File('image');
        $element->setLabel('Seleziona l\'immagine');
        $form->addElement($element, 'image');

        //submit
        $form->addElement('submit', 'submit');
        $submitButton = $form->getElement('submit');
        $submitButton->setLabel('Modifica l\'immagine!');

        return $form;
    }

    public function createSuccessDiscoAction()
    {
        $isErrorForm = 0; // for now i dont have errors on form
        $isErrorImg = 0; // no eror on image
        $isErrorPiva = 0; // no error on piva
        $errorPiva = "";
        $errorForm = "";
        $errorImg = "";

        $piva = $this->_getParam('piva', 'guest');
        $form = $this->getDiscoForm($piva);

        // validating form
        if ($form->isValid($_POST)) {
            $title = $this->_request->getPost('titolo');
            $description = $this->_request->getPost('descrizione');
            //$description2 = $this->_request->getPost(tagedit);
            //$date = $this->_request->getPost('datep');
            $date = $this->_request->getPost('data_inizio');
            //$table = $this->_request->getPost('tavoli');
            //$bottle = $this->_request->getPost('bottle');
            //$piva=$this->_request->getPost('piva');
            $status = $this->_request->getPost('status');
            $pren = $this->_request->getPost('prenorno');
        } else {
            $isErrorForm = 1;
        }
        //echo "descrizione1:  " . $description;
        //echo "data inizio:  " . $date;
        //$this->view->description=$description;
        //$this->view->description2=$description2;
        //echo "PRENOTAZIONE: " . $pren;

        //echo "<pre>" . print_r($this->_request->getParams()) ."<pre/>";

        // validating image
        
        $destDir = 'upload';
        $upload = new Zend_File_Transfer_Adapter_Http();
        $upload->setDestination($destDir);
        // set the validator
        $upload->addValidator('Count', false, 1)
                ->addValidator('ExcludeExtension', false, array('php', 'exe', 'sql', 'gif'))
                ->addValidator('Extension', false, 'jpg,png,jpeg');
                //->addValidator('FilesSize', false, array('min' => '1kB', 'max' => '400MB'));

        if ($upload->isValid()){
            if ($upload->receive()) {
                $file_name = $upload->getFileName('image');
            }
            else{ // i have error on receive
                $isErrorImg=1;
                $errorImg=$upload->getMessages();
                $errorImg=implode("\n", $errorImg);
            }

            }else{ // i have error on validation
                $isErrorImg=1;
                $errorImg=$upload->getMessages();
                $errorImg=implode("\n", $errorImg);
        }


        // validating piva
        require_once "models/Utility/Utility.php";

        $validPiva=Utility::isExistingPiva($piva,1);
        if(!$validPiva){ // not valid piva
                  $isErrorPiva=1;
                  $errorPiva="Error: la partita iva non e' presente nel database<br>";
        }

        if($isErrorForm==0 && $isErrorImg==0 && $isErrorPiva==0){ // no errors
            // i send the data
            //$title = $this->view->escape($title);
            $description = $this->view->escape($description);
//            $table = $this->view->escape($table);
//            $bottle = $this->view->escape($bottle);
            $piva = $this->view->escape($piva);

            $title=stripslashes($title);
            $description=stripslashes($description);

            $data = array("titolo" => $title,
             "descrizione" => $description,
             "data_inizio" => $date,
             //"tavoli" => $table,
             //"bottle" => $bottle,
             "piva" => $piva,
             "status" => $status,
             "pren" => $pren
            );

            $disco = new Application_Model_DbTable_Administrator();

            // i save into the db
            // connection to the db
            //echo "printr:    " . print_r($data);
            $id=$disco->addEventDisco($data);
			//$id = $db->lastInsertId();
			$data['id']=$id;
            // getting data for the thumb name
            //$data=$disco->getEventDisco($title,$piva,'*','1');

            // making thumbnails
            Utility::makeThumbEvent($data, $file_name, $destDir,1);

            /*$tweet = Utility::createTweet($title,$description);
            $twitterClient = new Application_Model_TwitterClient();
            $result        = $twitterClient->authenticate();
            $twitter       = $twitterClient->getTwitter();
            $twitter->status->update($tweet);
            $response      = $twitter->account->endSession();
			*/
            /*
                    $status = $twitter->status->userTimeline();
                    $this->view->statusMsgs = $status;

                    // Get friend timeline
                    $friendTimeline  = $twitter->status->friendsTimeline();
                    $this->view->statusFriendMsgs = $friendTimeline;
             *
             */

         }else{ // i have errors
            $this->view->form = $form;
         }

        // se the var for the view
        $this->view->isErrorForm = $isErrorForm;
        $this->view->isErrorImg = $isErrorImg;
        $this->view->isErrorPiva = $isErrorPiva;
        $this->view->errorPiva=$errorPiva;
        $this->view->errorForm=$errorForm;
        $this->view->errorImg=$errorImg;
    }

   public function deleteDiscoEventAction($id, $enable)
    {
        // delete conditions
        $table='edisco';
        $newValue = array("status"=> $enable);
        $condition='id=' . $id;

        // updating the table
        $disco = new Application_Model_DbTable_Administrator();
        $disco->updateEventDisco($table,$newValue,$condition);
    }

    public function showDiscoEventAction()
    {
        // db part
        //Check if the user is logged in
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            echo "Non sei autorizzato.";

        } else {
            //Fetch the user's id
            //Fetch the users information
            $id = $auth->getIdentity()->id;
            $piva = $this->_getParam('piva','guest');


            $admin = new Application_Model_DbTable_Administrator();
            $eventL = $admin->getEventDiscoByPiva($piva);
            
            // filter the event to get only the new event ( within 2 weeks or new events)
            $eventList;
            $key=0;
            foreach ($eventL as $event ){
                    //var_dump($event['data_inizio']);
                    $yyyy=strtok($event['data_inizio'],"-");
                    $mm=strtok("-");
                    $dd=strtok("-");
                    //echo "year: ". $yyyy ."mm: " . $mm . "dd: ". $dd;;
                    $data_inizio=mktime(0,0,0,$mm,$dd,$yyyy);
                    $timestamp=time();
                    // i dont want hour and seconds
                    $today=mktime(0,0,0,date("m",$timestamp),date("d",$timestamp),date("Y",$timestamp));
                    // if the event has still to occour i keep it
                    if($event['status']==0){ // if the event is unactive
                        if($data_inizio>=$today){
                            $eventList[$key]=$event; // i add it
                            $key++;
                        }
                        else{ // i check if is within 2 weeks
                            $compare=$today -(60*60*24*14); // i remove 2 weeks
                            if($compare<=$data_inizio){ // the event is within 2 weeks, good
                                $eventList[$key]=$event;
                                $key++;
                            }
                        }
                    }
                    else{ // i just add it
                        $eventList[$key]=$event; 
                        $key++;
                    }
                    //print_r($eventList);
            }

            /*
             * mando alla view gli eventi associati alla
             * disco con piva = $piva
             * associate all'autenticato.
             * e in data valida
             */
            $this->view->piva = $piva;
            $this->view->event = $eventList;
        }
    }

    public function handleDiscoEventAction()
    {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
        echo "Non sei autorizzato.";
        $this->_forward('index');
        }

        // action body
        $params = $this->_request->getParam('id');

        $id_admin = $auth->getIdentity()->id;
        $piva = $this->_getParam('piva', 'guest');

        // string parsing
        $result = explode("_", $params);

        //echo "params" . $params;
        //echo "piva" . $piva;

        if (is_null($params)) { // if i dont have params i just show
        $this->_forward('index');
        
        } elseif ($result[0] == 1) { // if i have to edit
        $id = $result[1];

        // this query is used to get the data to show in the edit form
        $disco = new Application_Model_DbTable_Administrator();
        $discoList = $disco->getEventDisco('*', '*', $id, '0');
        $form=$this->getDiscoTextForm($discoList, $id, $piva);
        $this->view->form = $form;

        } elseif ($result[0] == 2) { // else i have to just to modify images
       
        // editing images
        require_once "models/Utility/Utility.php";
        $id_evento = $result[1];

        $form = $this->getDiscoImageForm($id_evento);

        $this->view->form = $form;

        } else {
        // i get the id
        $id = $result[1];
        // get if enable or no
        $enable = $result[2];
        $this->deleteDiscoEventAction($id, $enable);
        //$this->_helper->viewRenderer->setNoRender();
        $this->_forward('show-disco-event');
        }

    }

    public function editSuccessDiscoAction()
    {

        $isError=0; // if i have error on the form
        
        $piva = $this->_getParam('piva','guest');
        $id=$this->_request->getParam('id');
        // this query is used to get the data to show in the edit form
        $disco = new Application_Model_DbTable_Administrator();
        $discoList = $disco->getEventDisco('*', '*', $id, '0');
        // this form is used if i have errors
        $form=$this->getDiscoTextForm($discoList, $id, $piva);
       
        // action body
        if ($form->isValid($_POST)) {
            $title=$this->_request->getParam('titolo');
            $description=$this->_request->getParam('descrizione');
            $date=$this->_request->getParam('data_inizio');
           // $table=$this->_request->getParam('tavoli');
           // $bottle=$this->_request->getParam('bottle');
    //        $piva=$this->_request->getParam('piva');
            $status=$this->_request->getParam('status');
            $pren=$this->_request->getParam('prenorno');

            // i send the data
            //$title = $this->view->escape($title);
            $description = $this->view->escape($description);
            //$table = $this->view->escape($table);
            //$bottle = $this->view->escape($bottle);
            $piva = $this->view->escape($piva);
        }
        else
            $isError=1;

        $title=stripslashes($title);
        $description=stripslashes($description);
        
        // the condition for the update query
        $data = array( "titolo" => $title,
            "descrizione" => $description,
            "data_inizio" => $date,
            //"tavoli" => $table,
            //"bottle" => $bottle,
            "piva" => $piva,
            "status" => $status,
            "pren" => $pren
        );

        // db connection
        $table='edisco';
        $condition='id=' . $id;

        if($isError==0){
            $disco = new Application_Model_DbTable_Administrator();
            $disco->updateEventDisco($table,$data,$condition);
        }
        else
            $this->view->form=$form;

        $this->view->isError=$isError;
       
    }

    public function editSuccessDiscoImageAction()
    {
        // action body

        $isErrorImg = 0; // no eror on image
        $errorImg = "";

        $id_event = $this->_getParam('id', 'guest');
        $form = $this->getDiscoImageForm($id_event);

        // validating image
        $destDir = 'upload';
        $upload = new Zend_File_Transfer_Adapter_Http();
        $upload->setDestination($destDir);
        // set the validator
        $upload->addValidator('Count', false, 1)
                ->addValidator('ExcludeExtension', false, array('php', 'exe', 'sql', 'gif'))
                ->addValidator('Extension', false, 'jpg,png,jpeg');
                //->addValidator('FilesSize', false, array('min' => '1kB', 'max' => '400MB'));

        if ($upload->isValid()){
            if ($upload->receive()) {
                $file_name = $upload->getFileName('image');
            }
            else{ // i have error on receive
                $isErrorImg=1;
                $errorImg=$upload->getMessages();
                $errorImg=implode("\n", $errorImg);
            }

            }else{ // i have error on validation
                $isErrorImg=1;
                $errorImg=$upload->getMessages();
                $errorImg=implode("\n", $errorImg);
        }

        //making thumb
        require_once "models/Utility/Utility.php";

        if($isErrorImg==0){ // no errors
        // i make the thumb
            
        $admin = new Application_Model_DbTable_Administrator();

        $data = $admin->getEventDisco('*', '*', $id_event, 0);

        // making thumbnails
        Utility::makeThumbEvent($data, $file_name, $destDir,0);


         }else{ // i have errors
            $this->view->form = $form;
         }

        // set the var for the view
        $this->view->isErrorImg = $isErrorImg;
        $this->view->errorImg=$errorImg;
        
    }

    public function clearOldEventsAction()
    {
        // action body
        $pass=$this->_getParam("pass","");
        
        if($pass=='p04rdt24'){
        $disco = new Application_Model_DbTable_Administrator();
        $events=$disco->showAllDiscoEvent();
        
        foreach($events as $event){
            if($event['status']==1){ // if active
                
                //var_dump($event['data_inizio']);
                $yyyy=strtok($event['data_inizio'],"-");
                $mm=strtok("-");
                $dd=strtok("-");
                //echo "year: ". $yyyy ."mm: " . $mm . "dd: ". $dd;;
                $data=mktime(0,0,0,$mm,$dd,$yyyy);
                $timestamp=time();
                // i dont want hour and seconds
                $today=mktime(0,0,0,date("m",$timestamp),date("d",$timestamp),date("Y",$timestamp));
                

                echo "DATA: " . date("Y-m-d H:i:s", $data);
                echo "   TODAY. ". date("Y-m-d H:i:s", $today);

                if($data>=($today - 60*60*12)) { // the event has still to occour - 1 day
                    // do nothing
                    echo "_____ data: " . $data . "today:" . ($today - 60*60*12) . "_____";
                }else{ // i need to unable the event
                    // prepare the data
                    $data= array(
                        "titolo" => $event['titolo'],
                        "descrizione" => $event['descrizione'],
                        "data_inizio" => $event['data_inizio'],
                        //"tavoli" => $event['tavoli'],
                        //"bottle" => $event['bottle'],
                        "piva" => $event['piva'],
                        "status" => 0,
                    );
                    //print_r($data);
                    
                    // save the data
                    $condition="id='".$event['id']."'";
                    //echo $condition;
                    $disco->updateEventDisco('edisco', $data, $condition);
                    echo "event " . $event['titolo'] . " successfully disabled";
                }
            }
        }//end foreach
        
        $this->view->print="Cancellazione funzionata!";
      }
      else
      {
        $this->view->print="Cancellazione non funzionata!";
      }
    
    }

}//end controller